<template>
  <div class="edit-password">
    <NavBar>
      <template #default>
        修改密码
      </template>
    </NavBar>

    <!-- 密码修改表单 -->
    <div class="edit-section">
      <div class="section-header">密码修改</div>
      <el-form :model="form" :rules="rules" ref="passwordForm" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="form.oldPassword"
            placeholder="请输入当前密码"
            type="password"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            placeholder="6-100位字符"
            type="password"
            show-password
            clearable
          />
          <div class="password-tips">
            密码长度需6-100位字符
          </div>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            placeholder="请再次输入新密码"
            type="password"
            show-password
            clearable
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 保存按钮 -->
    <div class="save-btn" @click="handleSubmit">
      确认修改
    </div>
  </div>
</template>

<script setup>
import NavBar from '../../components/common/NavBar.vue';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { updatePassword } from '@/api/UserApi';

const router = useRouter();
const passwordForm = ref(null);

// 表单数据
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 验证规则
const validateOldPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入原密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'));
  } else {
    callback();
  }
};

const validateNewPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'));
  } else if (value.length < 6) {
    callback(new Error('密码长度至少6位'));
  } else if (value === form.value.oldPassword) {
    callback(new Error('新密码不能与原密码相同'));
  } else {
    callback();
  }
};

const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== form.value.newPassword) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

const rules = {
  oldPassword: [
    { validator: validateOldPassword, trigger: 'blur' }
  ],
  newPassword: [
    { validator: validateNewPassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 提交修改
// 组件中使用
const handleSubmit = async () => {
    try {
        await passwordForm.value.validate();

        const userInfo = JSON.parse(localStorage.getItem('userAccount'));
        const response = await updatePassword({
            userId: userInfo.userId,
            oldPassword: form.value.oldPassword,
            newPassword: form.value.newPassword
        });

        if (response.code === 1) { // 假设1表示成功
            ElMessage.success(response.msg || '密码修改成功');
            // 清除表单
            form.value = {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            };
            // 返回上一页
            setTimeout(() => router.back(), 1500);
        } else {
            ElMessage.error(response.msg || '密码修改失败');
        }
    } catch (error) {
        console.error('密码修改失败:', error);
        const errorMsg = error.response?.msg ||
                        error.response?.message ||
                        error.message ||
                        '密码修改失败';
        ElMessage.error(errorMsg);
    }
};
</script>

<style scoped>
.edit-password {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 60px;
}

.edit-section {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
}

.section-header {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.save-btn {
  margin: 20px 15px;
  padding: 12px 0;
  background-color: #ff5000;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

.save-btn:active {
  opacity: 0.9;
}

.password-tips {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.el-form {
  padding-top: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>